import hashlib
import json
import os
import time

import requests
from PyQt5 import QtNetwork
from PyQt5.QtCore import QUrl
from PyQt5.QtNetwork import QNetworkAccessManager, QNetworkRequest
from PyQt5.QtWidgets import QWidget, QMessageBox

from Ui_sim import Ui_Form_SIM
from LoadingProgress import LoadingProgress



class Form_SIM(QWidget):
    def __init__(self, parent=None):
        super(Form_SIM, self).__init__(parent)
        self.ui = Ui_Form_SIM()
        self.ui.setupUi(self)
        self.set_ui()
        self.appid = '7857caedb7b44ccea9902eb95d770b93'
        self.secret = '6865c030e7584f1aa18b52e053ad7825'
        self.iccid = ''
        self.ui.lineEdit_APPID.setText(self.appid)
        self.ui.lineEdit_Secret.setText(self.secret)
        self.LoadingProgress = LoadingProgress()
        # 898604b0162380152720

    def handleResponse(self, reply):
        self.LoadingProgress.stop()
        err = reply.error()
        if err == QtNetwork.QNetworkReply.NoError:
            res = reply.readAll()
            jsonBody = json.loads(str(res, 'utf-8'))
            print('响应内容', jsonBody)
            self.ui.textBrowser.setText(json.dumps(jsonBody, indent=4, ensure_ascii=False))
            resCode = jsonBody.get('code')
            if resCode == 500:
                print('msg ', jsonBody.get('msg'))
                QMessageBox.critical(self, '错误', jsonBody.get('msg'))
            elif resCode == 200:
                # 运营商
                jsonData = jsonBody.get('data')
                operator = jsonData.get('operator')
                operatorText = str(operator)
                if operator == 0:
                    operatorText = '中国移动'
                elif operator == 1:
                    operatorText = '中国联通'
                elif operator == 2:
                    operatorText = '中国电信'
                elif operator == 99:
                    operatorText = '未知'
                self.ui.lineEdit_2.setText(str(operatorText))
                # 套餐名称
                self.ui.lineEdit_3.setText(str(jsonData.get('supplierName')))
                # 状态
                status = jsonData.get('state')
                statusText = str(status)
                if status == 0:
                    statusText = '正常'
                elif status == 2:
                    statusText = '停机'
                elif status == 99:
                    statusText = '其他'
                self.ui.lineEdit_4.setText(str(statusText))
                # 到期时间
                self.ui.lineEdit_9.setText(str(jsonData.get('endTime')))
                # 流量总量
                self.ui.lineEdit_10.setText(str(jsonData.get('total')))
                # 使用流量
                self.ui.lineEdit_11.setText(str(jsonData.get('used')))
                # 剩余流量
                self.ui.lineEdit_12.setText(str(jsonData.get('leftTraffic')))
                # 供应商
                supplier = jsonData.get('supplier')
                supplierText = str(supplier)
                if supplier == 0:
                    supplierText = '中国移动'
                elif supplier == 1:
                    supplierText = '中国电信'
                elif supplier == 2:
                    supplierText = '上海旭宇'
                elif supplier == 3:
                    supplierText = '上海量讯'
                elif supplier == 4:
                    supplierText = '河南硕朗'
                elif supplier == 5:
                    supplierText = '上海商粲'
                elif supplier == 6:
                    supplierText = '深圳为真'
                elif supplier == 7:
                    supplierText = '创之汇'
                elif supplier == 8:
                    supplierText = '创之汇'
                elif supplier == 9:
                    supplierText = '讯众'
                else:
                    supplierText = '未知'
                self.ui.lineEdit_13.setText(str(supplierText))
                # 查询时间
                self.ui.lineEdit_14.setText(str(jsonData.get('addTime')))
        else:
            print("Error", err)
            print(reply.errorString())
            QMessageBox.critical(self, '错误', '请求超时，请重试')
        self.ui.pushButton_search.setEnabled(True)
        self.ui.pushButton_update.setEnabled(True)


    def set_ui(self):
        self.ui.pushButton_search.clicked.connect(self.search_sim)
        self.ui.pushButton_update.clicked.connect(self.update_sim)
        self.ui.lineEdit_2.setReadOnly(True)
        self.ui.lineEdit_3.setReadOnly(True)
        self.ui.lineEdit_4.setReadOnly(True)
        self.ui.lineEdit_9.setReadOnly(True)
        self.ui.lineEdit_10.setReadOnly(True)
        self.ui.lineEdit_11.setReadOnly(True)
        self.ui.lineEdit_12.setReadOnly(True)
        self.ui.lineEdit_13.setReadOnly(True)
        self.ui.lineEdit_14.setReadOnly(True)
        self.ui.textBrowser.setReadOnly(True)

    def ui_clear(self):
        # 清空
        self.ui.lineEdit_2.clear()
        self.ui.lineEdit_3.clear()
        self.ui.lineEdit_4.clear()
        self.ui.lineEdit_9.clear()
        self.ui.lineEdit_10.clear()
        self.ui.lineEdit_11.clear()
        self.ui.lineEdit_12.clear()
        self.ui.lineEdit_13.clear()
        self.ui.lineEdit_14.clear()
        self.ui.textBrowser.clear()
        self.ui.pushButton_search.setEnabled(False)
        self.ui.pushButton_update.setEnabled(False)

    def message_check(self):
        self.iccid = self.ui.lineEdit.text()
        self.appid = self.ui.lineEdit_APPID.text()
        self.secret = self.ui.lineEdit_Secret.text()
        if len(self.iccid) == 0:
            QMessageBox.critical(self, '错误', '请输入ICCID')
            return False
        elif len(self.appid) == 0:
            QMessageBox.critical(self, '错误', '请输入APPID')
            return False
        elif len(self.secret) == 0:
            QMessageBox.critical(self, '错误', '请输入Secret')
            return False
        else:
            return True

    def search_sim(self):
        self.ui_clear()
        # 刷新
        self.repaint()
        if self.message_check():
            md5 = hashlib.md5()
            md5.update(self.secret.encode('utf-8'))
            secretMd5 = md5.hexdigest().upper()
            url = QUrl("https://api.xiangyuniot.com/api/third/cardInfo/v1.0/query/{}".format(self.iccid))
            self.req = QtNetwork.QNetworkRequest(url)
            self.req.setHeader(QtNetwork.QNetworkRequest.ContentTypeHeader, 'application/x-www-form-urlencoded')
            self.req.setRawHeader('appId'.encode('utf-8'), self.appid.encode('utf-8'))
            self.req.setRawHeader('secret'.encode('utf-8'), secretMd5.encode('utf-8'))
            self.req.setRawHeader('auth-version'.encode('utf-8'), '1.0'.encode('utf-8'))
            self.manager = QtNetwork.QNetworkAccessManager()
            self.manager.finished.connect(self.handleResponse)
            self.manager.get(self.req)
            print('获取请求的网址：', self.req.url().toString())
            print('请求的头部：', self.req.rawHeaderList())
            self.LoadingProgress.start()

    def update_sim(self):
        self.ui_clear()
        # 刷新
        self.repaint()
        if self.message_check():
            md5 = hashlib.md5()
            md5.update(self.secret.encode('utf-8'))
            secretMd5 = md5.hexdigest().upper()
            url = QUrl("https://api.xiangyuniot.com/api/third/cardInfo/v1.0/update")
            self.req = QtNetwork.QNetworkRequest(url)
            self.req.setHeader(QtNetwork.QNetworkRequest.ContentTypeHeader, 'application/json')
            self.req.setRawHeader('appId'.encode('utf-8'), self.appid.encode('utf-8'))
            self.req.setRawHeader('secret'.encode('utf-8'), secretMd5.encode('utf-8'))
            self.req.setRawHeader('auth-version'.encode('utf-8'), '1.0'.encode('utf-8'))
            self.manager = QtNetwork.QNetworkAccessManager()
            self.manager.finished.connect(self.handleResponse)
            body = json.dumps({"iccid": self.iccid})
            self.manager.post(self.req, body.encode('utf-8'))
            print('获取请求的网址：', self.req.url().toString())
            # 打印出请求的头部和值
            print('请求的头部：', self.req.rawHeaderList())
            # 打印出请求的body
            print('请求的body：', body)
            self.LoadingProgress.start()